package com.example.research.service;

import com.example.research.entity.User;
import com.example.research.entity.VerticalProject;
import com.example.research.entity.HorizontalProject;
import com.example.research.entity.Paper;
import com.example.research.mapper.VerticalProjectMapper;
import com.example.research.mapper.HorizontalProjectMapper;
import com.example.research.mapper.PaperMapper;
import com.example.research.mapper.AuditRecordMapper;
import com.example.research.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class DashboardService {

    @Autowired
    private VerticalProjectMapper verticalProjectMapper;

    @Autowired
    private HorizontalProjectMapper horizontalProjectMapper;

    @Autowired
    private PaperMapper paperMapper;

    @Autowired
    private AuditRecordMapper auditRecordMapper;

    @Autowired
    private UserMapper userMapper;

    public Map<String, Object> getStats(String username) {
        Map<String, Object> stats = new HashMap<>();

        // 根据username获取用户信息
        User user = userMapper.selectByUsername(username);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        if ("ADMIN".equals(user.getRole())) {
            // 管理员看到所有数据
            stats.put("verticalProjects", verticalProjectMapper.countAll());
            stats.put("horizontalProjects", horizontalProjectMapper.countAll());
            stats.put("papers", paperMapper.countAll());
            stats.put("pendingAudits", auditRecordMapper.countPending());
        } else if ("TEACHER".equals(user.getRole())) {
            // 教师看到所有数据，但待审核只看自己能审核的
            stats.put("verticalProjects", verticalProjectMapper.countAll());
            stats.put("horizontalProjects", horizontalProjectMapper.countAll());
            stats.put("papers", paperMapper.countAll());
            stats.put("pendingAudits", auditRecordMapper.countPendingForTeacher(user.getId()));
        } else {
            // 学生只看到自己的数据
            stats.put("verticalProjects", verticalProjectMapper.countByUserId(user.getId()));
            stats.put("horizontalProjects", horizontalProjectMapper.countByUserId(user.getId()));
            stats.put("papers", paperMapper.countByUserId(user.getId()));
            stats.put("pendingAudits", auditRecordMapper.countPendingByUserId(user.getId()));
        }

        return stats;
    }

    public Map<String, Object> getRecentItems(String username) {
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> items = new ArrayList<>();

        // 根据username获取用户信息
        User user = userMapper.selectByUsername(username);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        if ("ADMIN".equals(user.getRole()) || "TEACHER".equals(user.getRole())) {
            // 管理员和教师看到最近提交的所有项目
            List<VerticalProject> recentVertical = verticalProjectMapper.findRecentSubmissions(5);
            List<HorizontalProject> recentHorizontal = horizontalProjectMapper.findRecentSubmissions(5);
            List<Paper> recentPapers = paperMapper.findRecentSubmissions(5);

            // 合并并按时间排序
            for (VerticalProject vp : recentVertical) {
                Map<String, Object> item = new HashMap<>();
                item.put("id", vp.getId());
                item.put("title", vp.getProjectName());
                item.put("type", "vertical");
                item.put("auditStatus", vp.getAuditStatus());
                item.put("createTime", vp.getCreatedTime());
                item.put("submitter", vp.getProjectLeader());
                items.add(item);
            }

            for (HorizontalProject hp : recentHorizontal) {
                Map<String, Object> item = new HashMap<>();
                item.put("id", hp.getId());
                item.put("title", hp.getProjectName());
                item.put("type", "horizontal");
                item.put("auditStatus", hp.getAuditStatus());
                item.put("createTime", hp.getCreatedTime());
                item.put("submitter", hp.getProjectLeader());
                items.add(item);
            }

            for (Paper paper : recentPapers) {
                Map<String, Object> item = new HashMap<>();
                item.put("id", paper.getId());
                item.put("title", paper.getPaperTitle());
                item.put("type", "paper");
                item.put("auditStatus", paper.getAuditStatus());
                item.put("createTime", paper.getCreatedTime());
                item.put("submitter", paper.getFirstAuthor());
                items.add(item);
            }
        } else {
            // 学生只看到自己的项目
            List<VerticalProject> myVertical = verticalProjectMapper.findByUserId(user.getId(), 0, 3);
            List<HorizontalProject> myHorizontal = horizontalProjectMapper.findByUserId(user.getId(), 0, 3);
            List<Paper> myPapers = paperMapper.findByUserId(user.getId(), 0, 3);

            for (VerticalProject vp : myVertical) {
                Map<String, Object> item = new HashMap<>();
                item.put("id", vp.getId());
                item.put("title", vp.getProjectName());
                item.put("type", "vertical");
                item.put("auditStatus", vp.getAuditStatus());
                item.put("createTime", vp.getCreatedTime());
                items.add(item);
            }

            for (HorizontalProject hp : myHorizontal) {
                Map<String, Object> item = new HashMap<>();
                item.put("id", hp.getId());
                item.put("title", hp.getProjectName());
                item.put("type", "horizontal");
                item.put("auditStatus", hp.getAuditStatus());
                item.put("createTime", hp.getCreatedTime());
                items.add(item);
            }

            for (Paper paper : myPapers) {
                Map<String, Object> item = new HashMap<>();
                item.put("id", paper.getId());
                item.put("title", paper.getPaperTitle());
                item.put("type", "paper");
                item.put("auditStatus", paper.getAuditStatus());
                item.put("createTime", paper.getCreatedTime());
                items.add(item);
            }
        }

        // 按创建时间倒序排序，取前5个
        items.sort((a, b) -> {
            LocalDateTime dateA = (LocalDateTime) a.get("createTime");
            LocalDateTime dateB = (LocalDateTime) b.get("createTime");
            if (dateA == null && dateB == null) return 0;
            if (dateA == null) return 1;
            if (dateB == null) return -1;
            return dateB.compareTo(dateA);
        });

        if (items.size() > 5) {
            items = items.subList(0, 5);
        }

        result.put("items", items);
        return result;
    }
}
